//
//  ContentView.swift
//  IdleFish
//
//  Created by Ben on 2021/8/12.
//

import SwiftUI
import SDWebImageSwiftUI

struct ContentView: View {
    
    // 本期视频将上一期制作的简单的网络等待提示HUD接入到项目中
    @EnvironmentObject var hudState: BenHUDState
    
    // @State修饰的属性有一个作用，就是当该属性被修改时，会触发重新绘制界面
    @State var currTab: CustomTabbar = .home
    @StateObject var homeVM = HomeViewModel()
    @StateObject var customTabbarViewModel: CustomTabbarViewModel = CustomTabbarViewModel()
    
    // 把控制登录相关功能的ViewModel放到ContentView下,因为在所有tab对应的view中，都有可能触发登录、注册等功能，所以将UserManagerViewModel放到ContentView下，方便后续获取
    @StateObject var userManagerVM: UserManagerViewModel = UserManagerViewModel.shared
    @StateObject var initVM: InitViewModel = InitViewModel()

    @State var showIssue: Bool = false
    
    
    init() {
        UITabBar.appearance().isHidden = true
    }
    
    var body: some View {
        
        // 本视频通过SwiftUI来模仿实现闲鱼app，旨在学习SwiftUI的使用，我会尽量还原闲鱼的UI和各项功能，有些素材布局方面的差别还请见谅
        
        // 首先实现TabbarView
        
        GeometryReader { proxy in
            // ZStack是一个z轴方向叠加view的容器,alignment可以设置容器内的view按照哪个方向叠放
            ZStack(alignment: .bottom) {
                //TabView相当于UITabbarViewController，粗浅的对照
                TabView(selection: $currTab) {
                    
                    HomeView()
                        .tag(CustomTabbar.home)
                        .environmentObject(customTabbarViewModel)
                        .environmentObject(homeVM)
                        // 传递userManagerVM
                        .environmentObject(userManagerVM)


                    NicePlayView()
                        .tag(CustomTabbar.niceplay)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)

                        .background(Color.orange)

                    MessageView()
                        .tag(CustomTabbar.message)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)

                        .background(Color.secondary)

                    MineView()
                        .tag(CustomTabbar.mine)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .environmentObject(initVM)
                        .environmentObject(customTabbarViewModel)
                }
                
                // 从本期视频开始，着手完成用户相关功能，比如登录、注册、找回密码等
                
 
                // 创建自定义tabbarview，之所以创建自定义的tabbar是因为闲鱼发布闲置物品按钮有一个凸起的圆弧
                CustomTabbarView(safeEdgeInsets: proxy.safeAreaInsets, showIssue: $showIssue, currTab: $currTab)
                    .opacity(customTabbarViewModel.atFront ? 1 : 0)
                // 再让tabbarView本身y轴偏移相同的高度,空白问题解决，接下来正式进入用户相关功能的开发
                // 用户相关功能大概会出三到四个视频
                    .offset(y: proxy.safeAreaInsets.bottom)
                
                // 首页推荐页面，设置自选频道
                HomeRecommendSetChannelView(safeAreaInsets: proxy.safeAreaInsets)
                    .offset(y: homeVM.showSetChannel ? 0 : proxy.size.height + proxy.safeAreaInsets.bottom)
                    .environmentObject(homeVM)
                
                IssueGoodsView(showIssueGoods: $showIssue)
                
            }
            
            // 网络等待消息弹窗
            .waitHUD(isWait: $hudState.isWait) {
                // 定义网络连接等待hud的样子
                VStack(spacing: 8) {
                    
                    AnimatedImage(name: hudState.customImageName)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 30, height: 30)
                    
                    if let msg = hudState.message {
                        
                        Text(msg)
                            .foregroundColor(.white)
                            .font(.system(size: 12, weight: .semibold))
                    }
                }
                .padding(20)
                .background(
                    
                    RoundedRectangle(cornerRadius: 10)
                        .fill(.black)
                )
            }
            // 一般消息弹窗
            .showMessageHUD(isPresented: $hudState.isPresented) {
                
                if let systemImageName = hudState.systemImageName {
                    
                    Label(hudState.message ?? "", systemImage: systemImageName)
                        .padding(.vertical, 8)
                        .padding(.horizontal, 12)
                        .background(
                            Capsule()
                                .fill(.white)
                        )
                } else {
                    
                    Text(hudState.message ?? "")
                        .foregroundColor(.white)
                        .font(.system(size: 20, weight: .bold))
                        .padding(.horizontal, 20)
                        .padding(.vertical, 10)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(
                                    Color.black.opacity(0.8)
                                )
                        )
                }
    
            }
        }
        .onAppear {
    
            Task {
                let token = userManagerVM.token
                if token.isEmpty == true {
                    return
                }

                await initVM.requestInit(token: token)

            }
        }
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

// 这里是hud的view扩展
extension View {
    
    // 网络等待hud
    func waitHUD<Content: View>(isWait: Binding<Bool>, @ViewBuilder content: () -> Content) -> some View {
        
        ZStack {
            
            self
            
            if isWait.wrappedValue {
                
                BenHUD(content: content)
                    .zIndex(1)
            }
        }
        
    }
    
    // 错误消息或其他消息弹出的弹窗hud
    func showMessageHUD<Content: View>(isPresented: Binding<Bool>, @ViewBuilder content: () -> Content) -> some View {
        
        ZStack {
            
            self
            
            if isPresented.wrappedValue {
                
                BenHUD(content: content)
                    
                    .zIndex(1)
            }
        }
        
    }
}
